import os
from playwright.sync_api import sync_playwright
from config import AUTH_FILE


def save_auth_state():
    """首次登录，手动输入账号密码后保存登录状态"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)  # 关闭无头模式
        context = browser.new_context()
        page = context.new_page()

        page.goto("https://www.xiaohongshu.com/")  # 访问小红书
        input("请手动登录后按回车...")  # 等待用户手动完成登录

        # 保存登录状态
        context.storage_state(path=AUTH_FILE)
        print(f"登录状态已保存到 {AUTH_FILE}")

        browser.close()


def load_auth_state():
    """如果已保存登录状态，则自动登录"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context(storage_state=AUTH_FILE)  # 读取登录状态
        page = context.new_page()

        page.goto("https://www.xiaohongshu.com/")  # 直接访问小红书，保持登录状态
        input("按回车键退出...")
        context.storage_state(path=AUTH_FILE)
        browser.close()


if __name__ == "__main__":
    if os.path.exists(AUTH_FILE):
        print("检测到已保存的登录状态，正在自动登录...")
        load_auth_state()
    else:
        print("未检测到登录状态，请手动登录...")
        save_auth_state()
